/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 驿站站点管理-驿站管理
 */
import React, { useRef, useEffect, useState } from 'react';
import { CloudUploadOutlined } from '@ant-design/icons';
import KbRemarksModal from '@/components/KbRemarksModal';
import KbUploadFile from '@/components/KbUploadFile/';
import DragTable from '@/components/DragTable';
import { getInnAdminJson, innAdminDelete, reOpenYz } from '@/services/yz/manage';
import ProTable from '@ant-design/pro-table';
import { Button, message, Space, Popconfirm } from 'antd';
import type { ConnectState } from '@/models/connect';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import type { TableProps } from 'antd/es/table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { TableListItem } from '@/components/_pages/yz/manage/index.d';
import type { YzManage } from './index.d';
import { getColumns, DataType } from './index.config';
import { getAddress } from './utils';
import { useSelector } from 'umi';

const typeMap: Record<string, number> = {
  siteSearch: 0,
  closeSite: 1,
  codeSearch: 2,
  rejected: 3,
};

const Index = ({ type, activeKey }: YzManage) => {
  const formRef = useRef<ProFormInstance>();
  const actionRef = useRef<ActionType>();
  const [options, setOptions] = useState([]);
  const [addressList, setAddressList] = useState<any[]>([]);
  const [tableParams, setTableParams] = useState<any>({});
  const [isUpLoadSearch, setIsUploadSearch] = useState<boolean>(false);

  const [record, setRecord] = useState<any>({});
  const [visible, setVisible] = useState<boolean>(false);
  const { winSize } = useSelector((state: ConnectState) => state.global);

  const onChange = (_: any, selectedOptions: any[] = []) => {
    const addressList_ = selectedOptions.map((item: any) => item.code);
    setAddressList(addressList_);
  };
  const upLoadCallBack = () => {
    setIsUploadSearch(true);
    setTimeout(() => {
      formRef.current?.submit();
    }, 1000);
  };

  const handleOption = (data: any) => {
    setRecord(data);
    setVisible(true);
  };

  const reOpen = (is_pass: number, dak_id: string, phone: string) => {
    return new Promise((resolve, rejected) => {
      reOpenYz({ dak_id, is_pass, phone }).then((res) => {
        if (res.code == 0) {
          resolve(null);
          actionRef.current?.reload();
        } else {
          rejected();
          message.error(res.msg);
        }
      });
    });
  };

  const handleChange: TableProps<DataType | any>['onChange'] = (pagination, filters, sorter) => {
    const { columnKey = '', order = '' }: any = sorter;
    if (columnKey === 'ytd_num') {
      let tableParams_ = {};
      if (order) {
        tableParams_ = {
          is_sort: '1',
          sort_by: order === 'ascend' ? '0' : '1',
        };
      } else {
        tableParams_ = {};
      }
      setTableParams(tableParams_);
    }
  };

  const columns: ProColumns<TableListItem>[] = [
    ...getColumns({ activeKey, options, setOptions, onChange, actionRef }),
    {
      title: '其他',
      fixed: 'right',
      align: 'center',
      valueType: 'option',
      width: winSize === 'xs' ? 80 : 130,
      render: (_, record_) => {
        const { closeMsg = [] } = record_;
        return (
          <Space direction='vertical'>
            {closeMsg[0] && closeMsg[0].id ? (
              <Popconfirm
                title={`${
                  closeMsg[0] && closeMsg[0].reason ? closeMsg[0].reason : '确认关闭消息吗？'
                }`}
                onConfirm={innAdminDelete}
              >
                <a>申请关闭消息</a>
              </Popconfirm>
            ) : null}
            {activeKey === 'rejected' && (
              <Popconfirm
                title={'是否将该驿站移入‘区域内独立驿站’？'}
                onConfirm={reOpen.bind(null, 1, record_.dak_id, record_.phone)}
              >
                <a>设为独立驿站</a>
              </Popconfirm>
            )}
            <a onClick={handleOption.bind(null, record_)}>备注</a>
          </Space>
        );
      },
    },
  ];

  const requestTableData = async (areaList: string[], values: any) => {
    const {
      current,
      pageSize,
      area_type = '全部',
      isUpload,
      input_filter,
      create_at,
      has_concat_location,
    } = values;
    let { keywords = '' } = values;
    const [province, city, district, town] = areaList || [];
    if (isUpload) {
      keywords = 'YT_CODE_BATCH';
    }
    const reqData: {
      page: number;
      pageSize: number;
      keywords: string;
      province?: string;
      city?: string;
      district?: string;
      town?: string;
      type: number;
      area_type?: string;
      input_filter: string;
      is_sort?: string;
      sort_by?: string;
      has_concat_location?: string;
      create_at?: string;
      start_time?: string;
      end_time?: string;
    } = {
      page: current,
      pageSize,
      keywords,
      province,
      city,
      district,
      town,
      type: typeMap[activeKey],
      area_type,
      input_filter,
      ...tableParams,
    };
    if (create_at) {
      const [start_time, end_time] = create_at;
      reqData.start_time = start_time;
      reqData.end_time = end_time;
    }
    if (has_concat_location) {
      reqData.has_concat_location = has_concat_location;
    }
    const { code, data, msg } = await getInnAdminJson(reqData);
    if (code == 0) {
      return { data: data.result, total: data.total };
    } else {
      message.error(msg);
      return {};
    }
  };

  useEffect(() => {
    if (activeKey === 'siteSearch' && options.length == 0) {
      //避免切换tab是初始化地址列表
      getAddress({ id: '0' }, setOptions);
    }
    if (activeKey == type) {
      actionRef.current?.reload();
    }
  }, [activeKey, type]);

  return (
    <DragTable>
      <ProTable<TableListItem>
        actionRef={actionRef}
        formRef={formRef}
        rowKey='id'
        request={(values) => requestTableData(addressList, { ...values, isUpload: isUpLoadSearch })}
        columns={columns}
        options={false}
        pagination={{
          pageSize: 20,
          showQuickJumper: false,
          showSizeChanger: false,
        }}
        onChange={handleChange}
        scroll={{ x: 1550 }}
        search={
          !['closeSite', 'rejected'].includes(activeKey)
            ? {
                collapsed: false,
                collapseRender: () => false,
                optionRender: (_, { form }) => [
                  [
                    <Space key='search'>
                      <Button
                        onClick={() => {
                          if (activeKey === 'siteSearch') {
                            setAddressList([]);
                          }
                          form?.resetFields();
                          form?.submit();
                        }}
                      >
                        重置
                      </Button>
                      <Button
                        type='primary'
                        onClick={() => {
                          setIsUploadSearch(false);
                          form?.submit();
                        }}
                      >
                        查询
                      </Button>
                      {activeKey === 'codeSearch' ? (
                        <KbUploadFile
                          checkSize={5000}
                          onCallBack={upLoadCallBack}
                          checkType='checkFile'
                        >
                          <Button key='phone' type='primary' icon={<CloudUploadOutlined />}>
                            Excel批量上传自动查询
                          </Button>
                        </KbUploadFile>
                      ) : null}
                    </Space>,
                  ],
                ],
              }
            : false
        }
      />
      <KbRemarksModal
        modalTitle={`添加备注 ｜ ${record.dak_name} ${record.dak_name && '-'} ${record.phone}`}
        required
        visible={visible}
        setVisible={setVisible}
        formatDataMap={{
          label: '',
          remark: 'remark',
          user: 'user_name',
          time: 'created_at',
        }}
        api='/Inn/updateInnRemark'
        formData={{ dakId: record.dak_id, inn_name: record.dak_name }}
        listApi='/Inn/getRemarkList'
        listFormData={{ cm_id: record.dak_id }}
      />
    </DragTable>
  );
};

export default Index;
